(function () {})();

var sdk = {
  getUname: function () {
    var iframe = document.getElementById("myFrameId");
    var iframecont = iframe.contentWindow;
    iframecont.postMessage(
      { action: "getUname", info: "zhangsan" },
      "http://127.0.0.1:8081/b.html"
    );
  },
  sayHi: function (info) {
    console.log("sdk_a sayHi", info.msg);
  },
  colseChildIframe: function (data) {
    console.log("sdk_a colseChildIframe","子iframe触发父方法，让父页面，关闭子页面");
    console.log("接受来自子页面的参数", data);
    // 把iframe移除
    var iframe = document.getElementById("myFrameId");
    if(iframe){
        var tipId = document.getElementById("tipId")
        if(!tipId){
            var tipId = document.createElement("p");
            tipId.setAttribute("id", "tipId")
            tipId.innerText = "2秒后，即将关闭 iframe"
            tipId.style = "color:red"
            document.body.appendChild(tipId);
        }
        
        setTimeout(function(){
            iframe.remove();
            if(tipId){
                tipId.remove();
            }
        }, 2000);
    }
  },
};

// 打开iframe
function openIframe() {
  var myFrame = document.getElementById("myFrameId");
  if (myFrame == null) {
    var iframe = document.createElement("iframe");
    iframe.setAttribute("id", "myFrameId");
    iframe.setAttribute("name", "myFrame");
    iframe.setAttribute("src", "http://127.0.0.1:8081/b.html");
    document.body.appendChild(iframe);
  }

  initPostMessage();
}

// 初始化跨域请求
function initPostMessage() {
  //监听接收
  window.addEventListener("message", function (e) {
    var res = e;
    var data = e.data;
    var info = e.data.info;
    if (true) {
      switch (data.action) {
        case "sayHi":
          sdk.sayHi(info);
          break;
        case "getUname":
          sdk.getUname();
          break;
        case "colseChildIframe":
          sdk.colseChildIframe(data.data);
          break;
        default:
          return;
      }
    }
  });
}
